package com.javaweb.blogcite.service.Impl;

import com.javaweb.blogcite.controller.vo.ProjectView;
import com.javaweb.blogcite.mapper.ProjectMapper;
import com.javaweb.blogcite.pojo.Project;
import com.javaweb.blogcite.service.ProjectService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class ProjectServiceImpl implements ProjectService {
    @Resource
    private ProjectMapper projectMapper;

    @Override
    public List<ProjectView> listAllProject() {
        // 查询所有项目数据，返回 Project 类型的列表
        List<Project> projectList = projectMapper.listAllProject();
        List<ProjectView> projectViewList = new ArrayList<>();
        for (Project project : projectList) {
            ProjectView projectView = new ProjectView(project);
            projectViewList.add(projectView);
        }
        return projectViewList;
    }
//design by cb --删除项目
    @Override
    public boolean deleteProject(Integer id) {
        int rows = projectMapper.deleteById(id);
        return rows > 0;
    }
//end design by cb

//design by cb --修改项目
    @Override
    public boolean updateProject(Integer id, ProjectView projectView) {
        Project project = convertToProject(projectView,id);
        int rows = projectMapper.update(project);
        return rows > 0;
    }

    private Project convertToProject(ProjectView projectView,Integer id) {

        Project project = new Project();
        project.setId(id);
        project.setName(projectView.getName());
        project.setUrl(projectView.getUrl());
        project.setThumb(projectView.getThumb());
        project.setGithub(projectView.getGithub());
        project.setOrder(projectView.getOrder());
        project.setDescription(projectView.getDescription().toString());
        return project;
    }
    @Override
    public boolean addProject(ProjectView projectView) {
        Project project = new Project();
        project.setName(projectView.getName());
        project.setUrl(projectView.getUrl());
        project.setThumb(projectView.getThumb());
        project.setGithub(projectView.getGithub());
        project.setOrder(projectView.getOrder());
        project.setDescription(projectView.getDescription().toString().substring(1, projectView.getDescription().toString().length() - 1));
        int rows = projectMapper.insert(project);
        return rows > 0;
    }
}
